package com.nami.gchat.infra.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nami.gchat.infra.cache.grp.GroupCache;
import com.nami.gchat.domain.model.co.GrpInfoModel;
import com.nami.gchat.domain.repository.GroupRepository;

import com.nami.gchat.infra.convertor.GrpConvert;
import com.nami.gchat.infra.mapper.GroupMapper;
import com.nami.gchat.infra.orm.GroupDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class GroupRepositoryImpl implements GroupRepository {

    private final GroupMapper baseMapper;

    @Override
    public GrpInfoModel getGrpInfo(String appKey, String grpId) {
        if (StringUtils.isBlank(appKey) || StringUtils.isBlank(grpId)) {
            log.error("[grp-info] 查询失败，参数为空 appKey={}, grpId={}", appKey, grpId);
            return null;
        }
        GroupDO groupDO = baseMapper.selectOne(new LambdaQueryWrapper<GroupDO>()
            .eq(GroupDO::getAppKey, appKey)
            .eq(GroupDO::getGroupId, grpId));
        return GrpConvert.INSTANCE.convert(groupDO);
    }

    public GrpInfoModel getGrpInfoFromCacheOrDB(String appKey, String grpId) {
        GrpInfoModel grpDomain = GroupCache.get(grpId);
        if (grpDomain == null) {
            grpDomain = this.getGrpInfo(appKey, grpId);
            if (grpDomain == null) {
                return null;
            }
            GroupCache.add(grpId, grpDomain);
            return grpDomain.clone();
        }
        return grpDomain;

    }
}
